const fs = require("fs");
const schedule = require("node-schedule");
const { spawnSync } = require("child_process");
const https = require('https');
console.log("schedule init!");
updateComets();
schedule.scheduleJob(`0 0 1 * * ?`, async () =>
{
    console.log("schedule job start!");
    await updateComets();
    console.log("schedule job finish!");
});

function updateComets ()
{
    return new Promise(resolve =>
    {
        const file = fs.createWriteStream("./data/comets.txt");
        https.get("https://www.minorplanetcenter.net/iau/MPCORB/CometEls.txt", function (response)
        {
            response.pipe(file);
            file.on("finish", () =>
            {
                file.close();
                console.log("Download Completed");
                spawnSync(`mini-program-pack${process.platform === 'win32' ? '.cmd':''}`, ["-t", "./data/comets.txt", "-o", "./data/comets.wasm.br"]);
                // console.log("1");
                spawnSync(`git${process.platform === 'win32' ? '.exe':''}`, ["add", "-u", "./data/*"]);
                // console.log("2");
                // let info = execSync("git status -s");
                // console.log(info.toString());
                let now = new Date().toLocaleString();
                spawnSync(`git${process.platform === 'win32' ? '.exe':''}`,[`commit`, `-m`, `update:${now}`]);
                // console.log("3",ss.stderr.toString());
                spawnSync(`git${process.platform === 'win32' ? '.exe':''}`, ["push", "--set-upstream", "origin", "master"]);
                // console.log("4");
            });
        });
        setTimeout(resolve, 10000);
    })
}